package com.kye.base.utils;

import android.content.Context;
import android.net.NetworkInfo;

import com.github.pwittchen.reactivenetwork.library.rx2.Connectivity;
import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork;
import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.error.DefaultErrorHandler;
import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.strategy.SocketInternetObservingStrategy;

import io.reactivex.Observable;
import io.reactivex.functions.Function;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 23/12/2017
 * @updated : 23/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class NetworkMonitorUtils {

    public static Observable<Connectivity> networkObservable(Context context) {
        return ReactiveNetwork.observeNetworkConnectivity(context);
    }

    public static Function<Connectivity, Boolean> getConnectionFunction() {
        return new Function<Connectivity, Boolean>() {
            @Override
            public Boolean apply(Connectivity connectivity) throws Exception {
                NetworkInfo.State state = connectivity.getState();
                switch (state) {
                    case CONNECTED:
                    case CONNECTING:
                        return true;
                    case DISCONNECTED:
                    case DISCONNECTING:
                        return false;
                    default:
                        return false;
                }
            }
        };
    }

    public static Observable<Boolean> internetObservable() {
        SocketInternetObservingStrategy socketInternetObservingStrategy = new SocketInternetObservingStrategy();
        return socketInternetObservingStrategy
                .observeInternetConnectivity(
                        500,
                        1000,
                        "https://www.baidu.com",
                        80,
                        2000,
                        new DefaultErrorHandler());
    }
}
